# -*- coding: iso-8859-1 -*-
# file Collidable.py
# author Rocco Martino
#
############################################################################
#    Copyright (C) 2015 by Rocco Martino                                   #
#    martinorocco@gmail.com                                                #
#                                                                          #
#    This program is free software; you can redistribute it and/or modify  #
#    it under the terms of the GNU Lesser General Public License as        #
#    published by the Free Software Foundation; either version 2.1 of the  #
#    License, or (at your option) any later version.                       #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU Lesser General Public License for more details.                   #
#                                                                          #
#    You should have received a copy of the GNU Lesser General Public      #
#    License along with this program; if not, write to the                 #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

############################################################################
from . import RigidBody, CollisionParameters

from mathutils import Vector
############################################################################




############################################################################
# ........................................................................ #
# ........................................................................ #
############################################################################




############################################################################
# ........................................................................ #
class Collidable(RigidBody.RigidBody):





############################################################################
    TriMesh = False
############################################################################









############################################################################
    def __init__(self, obj, data):
        super(Collidable, self).__init__(obj, data)


        self.TriMesh = False


        if obj.game.collision_bounds_type == "CAPSULE":
            self.ClassName = "osgODE::Capsule"


        elif obj.game.collision_bounds_type == "BOX":
            self.ClassName = "osgODE::Box"


        elif obj.game.collision_bounds_type == "SPHERE":
            self.ClassName = "osgODE::Sphere"


        elif obj.game.collision_bounds_type == "CYLINDER":
            self.ClassName = "osgODE::Cylinder"


        elif obj.game.collision_bounds_type == "TRIANGLE_MESH":
            self.ClassName = "osgODE::TriMesh"
            self.TriMesh = True


        else:
            self.ClassName = "osgODE::UnsupportedCollisionBoundType"
            print("Unsupported collision bound type: %s" % obj.collision_bounds_type)
############################################################################




############################################################################
    def writeData(self, writer):
        super(Collidable, self).writeData(writer)






        collide_bits = 0
        category_bits = 0



        temp = 1

        for i in self.BlenderObject.game.collision_group:
            if i:
                category_bits = category_bits | temp
            temp = temp << 1



        temp = 1

        for i in self.BlenderObject.game.collision_mask:
            if i:
                collide_bits = collide_bits | temp
            temp = temp << 1



        writer.writeLine("CategoryBits 0x%x" %category_bits)
        writer.writeLine("CollideBits 0x%x" %collide_bits)
        writer.writeLine("GeometrySize %f %f %f" %(self.BlenderObject.dimensions.x, self.BlenderObject.dimensions.y, self.BlenderObject.dimensions.z))





        writer.moveIn("CollisionParameters TRUE")

        collision_parameters = CollisionParameters.CollisionParameters( self.BlenderObject, self.Data)

        collision_parameters.writeObject(writer)

        writer.moveOut("CollisionParameters TRUE")





        if self.TriMesh:


            vertex_array = self.readVertexArray()
            index_array = self.readIndexArray( vertex_array )


            VERTICES = "VertexArray %d"  % len(vertex_array)
            INDICES = "IndexArray %d"  % len(index_array)




            writer.moveIn(VERTICES)

            for v in vertex_array:
                writer.writeLine("%f %f %f" % (v.x, v.y, v.z))

            writer.moveOut(VERTICES)




            writer.moveIn(INDICES)


            for i in range( 0, len(index_array), 3 ):
                i1 = index_array[i]
                i2 = index_array[i+1]
                i3 = index_array[i+2]

                writer.writeLine( "%d %d %d" % (i1, i2, i3) )


            writer.moveOut(INDICES)
############################################################################




############################################################################
    def readVertexArray(self):

        vertex_array = []

        vertices = self.BlenderObject.data.vertices


        scale_vec = self.BlenderObject.matrix_local.to_scale()



        for v in vertices:
            vert = Vector(v.co)


            vert.x *= scale_vec.x
            vert.y *= scale_vec.y
            vert.z *= scale_vec.z


            vertex_array.append(vert)




        return vertex_array
############################################################################




############################################################################
    def readIndexArray(self, vertex_array):

        index_array = []

        faces = self.BlenderObject.data.polygons


        for f in faces:
            vertices = f.vertices
            num = len(vertices)


            if num == 3:
                index_array.append(vertices[0])
                index_array.append(vertices[1])
                index_array.append(vertices[2])

            elif num == 4:
                index_array.append(vertices[0])
                index_array.append(vertices[1])
                index_array.append(vertices[2])

                index_array.append(vertices[0])
                index_array.append(vertices[2])
                index_array.append(vertices[3])


            #else:
                #print("%s: only triangles and quads are supported: triangle not exported" %(self.BlenderObject.name, l))



            else:
                center = Vector()

                for i in vertices:
                    center = (center + vertex_array[i])

                center = center / float(num)


                vertex_array.append( center )

                center_idx = len( vertex_array ) - 1


                for i in range(num):

                    i2 = i+1

                    if i2 == num:
                        i2 = 0

                    index_array.append( center_idx )
                    index_array.append( vertices[i] )
                    index_array.append( vertices[i2] )



        return index_array
############################################################################




# ........................................................................ #
############################################################################
